// Jest Test Setup - 测试环境设置

import { jest } from '@jest/globals';

// 设置测试超时时间
jest.setTimeout(30000);

// Mock console methods to reduce noise in tests
const originalConsole = global.console;

beforeEach(() => {
    // 在每个测试前重置 console mocks
    global.console = {
        ...originalConsole,
        log: jest.fn(),
        info: jest.fn(),
        warn: jest.fn(),
        error: jest.fn(),
        debug: jest.fn()
    } as any;
});

afterEach(() => {
    // 在每个测试后恢复原始 console
    global.console = originalConsole;
    
    // 清理所有 mocks
    jest.clearAllMocks();
});

// 全局测试工具函数
global.createMockLogger = () => ({
    debug: jest.fn(),
    info: jest.fn(),
    warn: jest.fn(),
    error: jest.fn(),
    setLogLevel: jest.fn(),
    addLogCallback: jest.fn(),
    removeLogCallback: jest.fn(),
    getLogEntries: jest.fn().mockReturnValue([]),
    clearLogs: jest.fn(),
    getLogStats: jest.fn().mockReturnValue({})
});

global.createMockContext = (overrides = {}) => ({
    workspaceRoot: '/test/workspace',
    environment: {},
    timestamp: new Date('2023-01-01T00:00:00.000Z'),
    permissions: ['file:read', 'file:write', 'process:execute', 'memory:read', 'memory:write'],
    logger: global.createMockLogger(),
    ...overrides
});

// 设置环境变量
process.env.NODE_ENV = 'test';
process.env.AUGMENT_TEST_MODE = 'true';

// 处理未捕获的异常
process.on('unhandledRejection', (reason, promise) => {
    console.error('Unhandled Rejection at:', promise, 'reason:', reason);
});

process.on('uncaughtException', (error) => {
    console.error('Uncaught Exception:', error);
});

// 导出测试工具
export const testUtils = {
    createMockLogger: global.createMockLogger,
    createMockContext: global.createMockContext,
    
    // 创建模拟的工具执行结果
    createMockToolResult: (success = true, data = {}, error = null) => ({
        success,
        data: success ? data : undefined,
        error: !success ? error || { code: 'TEST_ERROR', message: 'Test error' } : undefined
    }),
    
    // 创建模拟的工具定义
    createMockToolDefinition: (name = 'test-tool', overrides = {}) => ({
        name,
        description: `Test tool: ${name}`,
        category: 'TEST',
        parameters: [],
        timeout: 5000,
        isAsync: true,
        ...overrides
    }),
    
    // 等待指定时间
    delay: (ms: number) => new Promise(resolve => setTimeout(resolve, ms)),
    
    // 创建临时文件路径
    createTempPath: (filename = 'test-file.txt') => `/tmp/test-${Date.now()}-${filename}`,
    
    // 验证错误对象
    expectError: (error: any, expectedCode?: string, expectedMessage?: string) => {
        expect(error).toBeInstanceOf(Error);
        if (expectedCode) {
            expect(error.code).toBe(expectedCode);
        }
        if (expectedMessage) {
            expect(error.message).toContain(expectedMessage);
        }
    }
};

// 声明全局类型
declare global {
    var createMockLogger: () => any;
    var createMockContext: (overrides?: any) => any;
}
